﻿using SyncFileCommon.Class;
using SyncFileCommon.Model;
using System.Runtime.CompilerServices;

namespace SyncFileCommon.BLL
{
    public class SyncPlanBLL
    {

        public static List<SyncPlanModel> SyncPlanList = null;

        /// <summary>
        /// 触发消息事件
        /// </summary>
        public static Action<string, string> MessageEvent;

        /// <summary>
        /// 获取同步计划列表
        /// </summary>
        /// <returns></returns>
        public static List<SyncPlanModel> SyncPlanListGet()
        {
            string _sSyncPlan = FileHelper.FileTextRead(FileHelper.GetRunPath() + "SyncPlan");
            List<SyncPlanModel> _syncPlan = JsonHelper.GetObjectFromJsonStr<List<SyncPlanModel>>(_sSyncPlan);
            SyncPlanList = _syncPlan;
            return _syncPlan;
        }

        /// <summary>
        /// 保存同步计划列表
        /// </summary>
        /// <param name="syncPlanList"></param>
        public static void SyncPlanListSave(List<SyncPlanModel> syncPlanList)
        {
            SyncPlanList = syncPlanList;
            string _sSyncPlanList = JsonHelper.GetJsonStrFromObject(syncPlanList);
            FileHelper.FileTextWrite(FileHelper.GetRunPath() + "SyncPlan", _sSyncPlanList);
        }

        /// <summary>
        /// 运行同步计划列表
        /// </summary> 
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void RunSyncPlan()
        {
            //获取同步计划列表
            if (SyncPlanList == null)
            {
                SyncPlanListGet();
            }

            if (SyncPlanList != null)
            {
                foreach (SyncPlanModel _syncPlan in SyncPlanBLL.SyncPlanList)
                {
                    if (new string[] { "R", "E" }.Contains(_syncPlan.RunType))
                    {
                        if (DateTime.Now < _syncPlan.BeginTime)
                        {
                            continue;
                        }

                        if (_syncPlan.LastRunTime == DateTime.MinValue)
                        {
                            _syncPlan.LastRunTime = _syncPlan.BeginTime.AddSeconds(-1 * _syncPlan.IntervalTime);
                        }

                        //计算任务执行时间
                        if ((DateTime.Now - _syncPlan.LastRunTime).TotalSeconds >= _syncPlan.IntervalTime)
                        {
                            if (_syncPlan.RunType == "E")
                            {
                                Task.Run(() =>
                                {
                                    if (!_syncPlan.IsRun)
                                    {
                                        _syncPlan.IsRun = true;
                                        SyncServerFile(_syncPlan.ID);
                                    }
                                }).ContinueWith(task =>
                                {
                                    _syncPlan.IsRun = false;
                                    // 任务完成后的代码
                                    _syncPlan.LastRunTime = DateTime.Now;
                                    SyncPlanBLL.SyncPlanListSave(SyncPlanList);
                                });


                            }

                            if (_syncPlan.RunType == "R")
                            {

                                if (_syncPlan.LastRunTime == DateTime.MinValue)
                                {
                                    _syncPlan.LastRunTime = _syncPlan.BeginTime;
                                }
                                long _s = -1;
                                int i = Convert.ToInt32(Math.DivRem(Convert.ToInt64((DateTime.Now - _syncPlan.LastRunTime).TotalSeconds), Convert.ToInt64(_syncPlan.IntervalTime), out _s));
                                if (_s <= 3)
                                {
                                    Task.Run(() =>
                                    {
                                        if (!_syncPlan.IsRun)
                                        {
                                            _syncPlan.IsRun = true;
                                            _syncPlan.LastRunTime = _syncPlan.LastRunTime.AddSeconds(i * _syncPlan.IntervalTime);
                                            SyncPlanBLL.SyncPlanListSave(SyncPlanList);
                                            SyncServerFile(_syncPlan.ID);
                                        }
                                    }).ContinueWith(task =>
                                    {
                                        _syncPlan.IsRun = false;
                                    });
                                }
                            }
                        }
                    }
                    else if (_syncPlan.RunType == "O")
                    {
                        if (DateTime.Now >= _syncPlan.BeginTime && (DateTime.Now - _syncPlan.BeginTime).TotalSeconds < 3)
                        {
                            Task.Run(() =>
                            {
                                if (!_syncPlan.IsRun)
                                {
                                    _syncPlan.IsRun = true;
                                    _syncPlan.LastRunTime = DateTime.Now;
                                    SyncPlanBLL.SyncPlanListSave(SyncPlanList);
                                    SyncServerFile(_syncPlan.ID);
                                }
                            });
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 执行同步计划
        /// </summary>
        /// <param name="id">同步计划ID</param>
        public static void SyncServerFile(long id)
        {
            if (SyncPlanList == null)
            {
                SyncPlanListGet();
            }

            if (SyncPlanList != null)
            {
                SyncPlanModel _syncPlan = SyncPlanBLL.SyncPlanList.Find(it => it.ID == id);
                if (_syncPlan != null)
                {
                    //创建与服务器的客户端连接同步文件
                    ClientBLL _client = new ClientBLL();
                    _client.SyncPlan = _syncPlan;
                    _client.DeleteFileDir = ConfigBLL.ClientConfig.DeleteFileDir;
                    if (MessageEvent != null)
                    {
                        _client.MessageEvent += MessageEvent;
                    }
                    _client.UserLogin = () =>
                    {
                        JsonHelper _json = new JsonHelper();
                        _json.AddVar("MessageType", "UserLogin");
                        _json.AddVar("UserName", _syncPlan.UserName);
                        _json.AddVar("Password", _syncPlan.Password);
                        SessionHelper.SendData(_client.Session, MessageHelper.CopyMessageHeadTo(MessageHead.JsonString, _json.JsonStr));
                    };
                    if (_client.ClientConnect(_syncPlan.ServerIP, _syncPlan.ServerPort))
                    {
                        
                    }
                   

                }
            }
        }

    }
}
